package com.task.platform.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.task.platform.bo.sys.po.User;
import com.task.platform.cache.MemoryCache;
import com.task.platform.exception.CustomException;
import com.task.platform.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.io.FileNotFoundException;
import java.net.URL;

@Service
@Slf4j
public class EmailServiceImp implements EmailService {

    @Autowired
    private JavaMailSender mailSender;


    @Autowired
    private UserService userService;

    @Value("${spring.mail.username}")
    private String emailFrom;

    @Override
    public void sendSimpleEmail(String to, String type) {
        try {
            if (to == null || to.isEmpty()) {
                throw new CustomException("Email address cannot be empty");
            }
            if (type == null || type.isEmpty()) {
                throw new CustomException("Type cannot be empty");
            }
            MemoryCache.getInstance().get(to);
            if (MemoryCache.getInstance().get(to) != null) {
                throw new CustomException("Verification code has been sent/**/, please check your email");
            }


            if ("2".equals(type)) {
                User userByEmail = userService.findUserByEmail(to);
                if (userByEmail != null) {
                    throw new CustomException("Email address has exist, please check your email");
                }
            }

            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(emailFrom);
            message.setTo(to);
            String verifyCode = getVerifyCode();
            String subject = getSubject(type);
            String text = getText(type, verifyCode);
            message.setSubject(subject);
            message.setText(text);
            mailSender.send(message);
            MemoryCache.getInstance().put(to, verifyCode);
        } catch (MailException e) {
            log.error("Failed to send email", e);
            // 抛出自定义异常
            throw new CustomException("Failed to send email");
        }
    }

    @Override
    public void sendSimpleRegisterEmail(String to, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(emailFrom);
        message.setTo(to);
        message.setSubject("account register notify");
        message.setText(text);
        mailSender.send(message);
    }

    @Override
    public String verifyEmailCode(String mail, String verifyCode) {
        String cacheVerifyCode = (String) MemoryCache.getInstance().get(mail);
        if (cacheVerifyCode == null) {
            throw new CustomException("Verification code has expired");
        }
        if (!cacheVerifyCode.equals(verifyCode)) {
            throw new CustomException("Verification code error");
        }

        User userByEmail = userService.findUserByEmail(mail);

        if (ObjectUtil.isEmpty(userByEmail)) {
            User user = new User();
            user.setUsername(mail);
            user.setEmail(mail);
            user.setPassword(RandomUtil.randomString(16));
            userService.save(user);
        }

        return userService.getJwt(userByEmail, verifyCode);
    }

    private String getSubject(String type) {
        if (type.equals("2")) {
            return "Welcome to the Task Platform";
        } else if (type.equals("1")) {
            return "Welcome to the Task Platform";
        }
        throw new CustomException("Invalid type");
    }

    private String getText(String type, String verifyCode) {
        // 构建富文本邮件内容
        URL url;
        try {
            url = ResourceUtils.getURL("classpath:static/mail.html");
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }

        String htmlContent = FileUtil.readString(url, "utf-8");
        if (type.equals("2") || type.equals("1")) {
            return htmlContent
                    .replace("${verifyCode}", verifyCode)
                    .replace("${title}","Your verification code is");
        } else {
            throw new CustomException("Invalid type");
        }
    }

    public String getVerifyCode() {
        return RandomUtil.randomNumbers(4);
    }

}
